package org.csu.mypetstore_seller.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.mypetstore_seller.domain.Seller;
import org.csu.mypetstore_seller.service.SellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class LoginController {

    @Autowired
    private SellerService sellerService;

    // 访问根路径时，如果未登录则跳转到登录页面
    @GetMapping("/")
    public String index(HttpSession session) {
        log.info("访问首页");
        if (session.getAttribute("seller") != null) {
            return "index";  // 已登录则显示主页
        }
        return "redirect:/login";  // 未登录则跳转到登录页
    }

    @GetMapping("/login")
    public String loginPage() {
        log.info("访问登录页面");
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model,
                        HttpSession session) {
        Seller seller = sellerService.login(username, password);
        if (seller != null) {

            // 登录成功
            log.info("用户{}登录成功", username);
            // 登录成功
            session.setAttribute("seller", seller);
            return "redirect:/main/main";
        } else {
            log.info("用户{}登录失败，用户名或密码错误", username);
            // 登录失败
            model.addAttribute("msg", "用户名或密码错误！");
            return "login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        log.info("用户退出登录");
        session.removeAttribute("seller");
        return "redirect:/login";
    }
}
